package edu.sctu.alex.June.day20150607;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 图形化的计时器
 *
 */
public class Test extends JFrame implements ActionListener,Runnable{
    JButton btn1; //添加按钮
    JButton btn2;
    JLabel time; //添加文本域
    int minute,seconds;
    Thread begin;
    boolean flag;   //添加判断 线程是否执行 的变量
    public Test(){
        btn1=new JButton("开始计时   ");
        btn2=new JButton("   停止计时");
        time=new JLabel(0+":"+0);
        minute=0;seconds=0;
        add(btn1);
        add(time);
        add(btn2);
        setLayout(new FlowLayout());
        setSize(250,250);
        setVisible(true);
        btn1.addActionListener(this); //监听按钮1 的动作
        btn2.addActionListener(this);
    }
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==btn1){
            if (begin != null && begin.isAlive()) {  //检查线程的状态
                begin.interrupt();
            }
            begin = new Thread(Test.this);

            minute=0;seconds=0;
            flag=true;
            begin.start();
        }
        else{
            flag=false;
        }
    }
    public void run(){
        while(flag){
            seconds++;
            if(seconds%60==0){    //60秒转换为分
                seconds=0;
                minute++;
            }
            time.setText(minute+" : "+seconds);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String args[]){
        new Test();
    }
}
